<template>
  <div class="app-container">
    <!-- Info Banner -->
    <div class="info-banner">
      <i class="el-icon-info" style="color: #0d73fc; font-size: 16px"></i>
      <span style="font-size: 14px">统计数据仅供参考，最终计费以实际消费记录为准。</span>
    </div>

    <el-card>
      <!-- Header -->
      <div class="header" style="font-size: 16px">
        <h2 style="font-weight: bold">消息发送统计</h2>
        <div class="header-actions">
          <!--        <span class="help-text">为什么消息一直处于"发送中"？或已了很久才收到？</span>-->
          <!--        <a href="#" class="link">点击了解</a>-->
          <!-- <button class="action-button primary">柱状图</button>
        <button class="action-button">折线图</button> -->
        </div>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">

        <el-form-item label="最近时间">
          <el-radio-group style="  " size="mini" v-model="radio2" @change="handlesj">
            <el-radio-button label="1">周</el-radio-button>
            <el-radio-button label="2">月</el-radio-button>
            <el-radio-button label="3">季</el-radio-button>
            <el-radio-button label="4">年</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- <span style="font-size: 14px;color: #787878;margin-left: 20px;">自定义：</span> -->
        <el-form-item label="" prop="startTime">
          <el-date-picker v-model="value1" type="daterange" align="right" unlink-panels size="mini" range-separator="至"
            :clearable="false" start-placeholder="开始日期" value-format="yyyy-MM-dd" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="消息通道" prop="smsChannel">
          <el-select v-model="queryParams.smsChannel" style="width: 100%;" filterable placeholder="消息通道" clearable
           >
            <el-option v-for="item in channelsList" :key="item.id" :label="item.name"
              :value="item.id.toString()"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="消息类型" prop="smsLx">
          <el-select v-model="queryParams.smsLx" placeholder="请选择消息类型" style="width: 100%"  clearable>
            <el-option label="普通短信" value="1" />
            <el-option label="智能短信" value="2" />
          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- Chart -->
      <div class="chart-container">
        <div ref="chart" style="height: 400px;"></div>

        <!-- Legend -->
        <div class="stats-summary">
          <div class="success-rate">
            <div class="rate-label">合计发送成功数（条）</div>
            <div class="rate-value success">{{ ((Number(fssl) - Number(sbsl)) / Number(fssl) * 100).toFixed(2) }}%</div>
            <div class="rate-detail">/ {{ fssl - sbsl }}</div>
          </div>
          <div class="success-rate">
            <div class="rate-label">合计发送失败数（条）</div>
            <div class="rate-value failure">{{ (Number(sbsl) / Number(fssl) * 100).toFixed(2) }}%</div>
            <div class="rate-detail">/ {{ sbsl }}</div>
          </div>
          <div class="chart-legend" style="font-size: 16px;">
            <div class="legend-item">
              通知类：{{ this.formtd.je1 }}元/条
            </div>
            <div class="legend-item">
              营销类：{{ this.formtd.je2 }}元/条
            </div>
            <div class="legend-item">
              图文类：{{ this.formtd.je3 }}元/条
            </div>
            <div class="legend-item">
              视频类：{{ this.formtd.je4 }}元/条
            </div>
          </div>
        </div>
      </div>
      <el-card>
        <span style="font-size: 16px;color: #787878;">消息发送详情</span>
        <el-divider></el-divider>
        <el-row :gutter="20" style="font-size: 18px;">
          <!-- <h3 style="margin-bottom: 10px;margin-top: 10px;margin-left: 10px;">统计信息汇总</h3> -->
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <div style="text-align: center;">
              <p>
                {{ this.formxq.sl1 }} 条
              </p>
              <p>
                通知消息
              </p>
            </div>
          </el-col>
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <h2>&nbsp;</h2>
            <div style="text-align: center;">
              <p>
                {{ this.formxq.sl2 }} 条
              </p>
              <p>
                营销消息
              </p>
            </div>
          </el-col>
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <h2></h2>
            <div style="text-align: center;">
              <p>
                {{ this.formxq.sl3 }} 条
              </p>
              <p>
                图文消息
              </p>
            </div>
          </el-col>
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <h2>&nbsp;</h2>
            <div style="text-align: center;">
              <p>
                {{ this.formxq.sl4 }} 条
              </p>
              <p>
                视频消息
              </p>

            </div>
          </el-col>
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <h2>&nbsp;</h2>
            <div style="text-align: center;">
              <p style="color: blue;">
                {{ this.formxq.cbje }} 元
              </p>
              <p>
                发送成本
              </p>

            </div>
          </el-col>
          <el-col :sm="24" :lg="4" style="padding-left: 20px">
            <h2>&nbsp;</h2>
            <div style="text-align: center;">
              <p style="color: red;">
                {{ this.formxq.xsje }} 元
              </p>
              <p>
                销售金额
              </p>

            </div>
          </el-col>
        </el-row>
      </el-card>
      <!-- Data Table -->
      <div class="data-table" v-if="false">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="sendTime" label="发送时间" sortable></el-table-column>
          <el-table-column prop="sentCount" label="发送总数（条）"></el-table-column>
          <el-table-column prop="successCount" label="发送成功数（条）"></el-table-column>
          <el-table-column prop="failureCount" label="发送失败数（条）"></el-table-column>
          <el-table-column prop="invalidCount" label="终端错误导致失败数数（条）"></el-table-column>
          <el-table-column prop="pendingCount" label="发送中（条）"></el-table-column>
          <el-table-column prop="effectiveRate" label="有效成功率"></el-table-column>
          <el-table-column prop="successRate" label="发送成功率"></el-table-column>
          <el-table-column prop="failureDetails" label="失败详情">
            <template slot-scope="scope">
              <el-button type="text" @click="showFailureDetails(scope.row)">
                查看失败详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getChannels } from "@/api/Sms/channels";
import { listChannels } from "@/api/Sms/channels";
import { Listfsl, Listfslfl, Listkhjg } from "@/api/Sms/SmsRecord";
import * as echarts from 'echarts'
import { GetMonA, GetMonB, GetDayA } from "@/api/public";
export default {
  name: 'SmsStatistics',
  dicts: ["audit_status"],
  data() {
    return {
      cmids: null,//选择的商机id
      userIds: [],//用户组，选人组件用
      // 通道表单
      formtd: {
        je1: '',
        je2: '',
        je3: '',
        je4: ''

      },
      // 发送详情数据
      formxq: {
        sl1: 0,
        sl2: 0,
        sl3: 0,
        sl4: 0,
        cbje: '0.00',
        xsje: '0.00'
      },

      // 消息通道表格数据
      channelsList: [],
      fssl: 0,
      sbsl: 0,
      radio2: 1, //1周，2月
      value1: [], //时间范围
      visitrecordsListfw: [],
      visitrecordsListfwcg: [],

      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        smsCustid: null,
        smsMobile: null,
        smsCountrycode: null,
        smsContent: null,
        smsHtml: null,
        smsStime: null,
        smsRtime: null,
        smsStatus: null,
        smsErrcode: null,
        smsErrdesc: null,
        smsExdata: null,
        smsType: null,
        rptType: null,
        smsAccount: null,
        smsSignature: null,
        smsChannel: null,
        smsLx: null,
        smsTmplid: null,
        smsExno: null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null,
        userId: null,
        smsName: null,
      },

      chart: null,
      tableData: [
        {
          sendTime: '2024-11-27',
          sentCount: 1,
          successCount: 1,
          failureCount: 0,
          invalidCount: 0,
          pendingCount: 0,
          effectiveRate: '100.0%',
          successRate: '100.0%',
          failureDetails: '查看失败详情'
        }
      ]
    }
  },
  created() {
    this.$nextTick(() => {
      this.getList();
    });
    listChannels().then(response => {
      this.channelsList = response.rows;
      this.total = response.total;

    });
  },
  mounted() {
    // this.initChart()
  },
  methods: {
    qk2() {
      this.queryParams.userId = null;
    },
    /** 选择客户相关事件 */
    showkh() {
      this.$nextTick(() => {
        this.$refs.selectry.show1();
      });
    },
    //绑定客户事件
    savery(val1, val2) {
      this.queryParams.smsName = val2;
      this.queryParams.userId = val1;
    },
    /** 查缓存询信息 */
    getList() {
      this.handlesj();
      //全部
      Listfsl(this.queryParams).then(response => {
        //  console.log(response.rows)
        this.visitrecordsListfw = [];
        this.visitrecordsListfw = response.rows;

        //成功发送的
        this.queryParams.smsStatus = "0";
        Listfsl(this.queryParams).then(response => {
          //  console.log(response.rows)
          this.visitrecordsListfwcg = [];
          this.visitrecordsListfwcg = response.rows;
          this.initChart();
        });
        // this.initChart();
      });

      window.addEventListener("resize", () => {
        this.chart.resize();

      });

    },
    initChart() {
      this.$nextTick(() => {

        var other1fw = [];//总数
        var other2fw = []; //日期
        var other1fwcg = [];//成功
        var zsl = 0;
        var cgzsl = 0;
        this.visitrecordsListfw.forEach(element => {
          zsl += parseInt(element.other1);
          other1fw.push(parseInt(element.other1));
          other2fw.push(this.parseTime(element.other2, '{m}-{d}'))
        });

        this.visitrecordsListfwcg.forEach(element => {
          cgzsl += parseInt(element.other1);
          other1fwcg.push(parseInt(element.other1));
        });

        this.fssl = zsl;
        this.sbsl = zsl - cgzsl;
        this.chart = echarts.init(this.$refs.chart)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: other2fw,
          },
          yAxis: {
            type: 'value',
            // max: 5
          },
          series: [
            {
              name: '发送总数',
              type: 'bar',
              data: other1fw,
              color: '#409EFF'
            },
            {
              name: '发送成功',
              type: 'bar',
              data: other1fwcg,
              color: '#67C23A'
            }
          ]
        }

        this.chart.setOption(option)
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.userId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      // Implement search logic
      this.radio2 = 11;
      this.$nextTick(() => {
        this.handlefw();
      });
    },
    showFailureDetails(row) {
      // Implement failure details modal
      console.log('Showing failure details for:', row)
    },
    //设置获取时间
    handlesj() {
      if (this.radio2 == 1) {
        this.Interval = 0;
        this.value1 = [];
        this.value1[0] = GetDayA(6);
        this.value1[1] = GetMonB();
      }

      if (this.radio2 == 2) {
        this.value1 = [];
        this.value1[0] = GetMonA(1);
        this.value1[1] = GetMonB();
      }

      if (this.radio2 == 3) {
        this.value1 = [];
        this.value1[0] = GetMonA(4);
        this.value1[1] = GetMonB();
      }
      if (this.radio2 == 4) {
        this.value1 = [];
        this.value1[0] = GetMonA(12);
        this.value1[1] = GetMonB();
      }

      if (this.value1[0] == undefined || this.value1[1] == undefined) {
        alert("请选择时间")
        return;
      }

      //主要计算时间差，根据根据结束时间去计算所有时间列表

      const start = new Date(this.value1[0]);
      const end = new Date(this.value1[1]);

      let dayNumber = Math.ceil((end - start) / (1000 * 60 * 60 * 24));
      this.queryParams.other3 = dayNumber;
      if (dayNumber >= 25) {
        var inval = Math.floor(dayNumber / 30);
        this.Interval = inval;
      }
      this.queryParams.other3 = dayNumber + 1;
      this.queryParams.other2 = this.value1[1]; //结束时间
      this.queryParams.other5 = this.value1[0]; //开始时间

      this.queryParams.smsStatus = null;
    },
    //选择周月年时触发
    handlefw(v) {
      var myChart = echarts.init(this.$refs.chart);
      // ... 这里是使用 myChart 的代码，比如配置和渲染图表 ...
      // 当你需要销毁这个实例时，调用 dispose 方法
      if (myChart != null && myChart.dispose) {
        myChart.dispose();
      }

      //消息发送统计
      this.getList();

      //选了通道时的操作
      if (this.queryParams.smsChannel != null && this.queryParams.smsChannel != '') {
        //获取消息成本价格
        getChannels(this.queryParams.smsChannel).then(response => {
          this.formtd.je1 = response.data["je1"];
          this.formtd.je2 = response.data["je2"];
          this.formtd.je3 = response.data["je3"];
          this.formtd.je4 = response.data["je4"];

          //分类消息数量
          this.queryParams.smsStatus = "0";
          Listfslfl(this.queryParams).then(response => {
            //  console.log(response.rows)

            let dxcbje = 0;
            this.formxq.cbje = '0.00';
            response.rows.forEach(item => {
              if (item.other2 == "1") {
                this.formxq.sl1 = item.other1;
                dxcbje += Number(this.formxq.sl1) * Number(this.formtd.je1)
              }
              if (item.other2 == "2") {
                this.formxq.sl2 = item.other1;
                dxcbje += Number(this.formxq.sl2) * Number(this.formtd.je2)
              }
              if (item.other2 == "3") {
                this.formxq.sl3 = item.other1;
                dxcbje += Number(this.formxq.sl3) * Number(this.formtd.je3)
              }
              if (item.other2 == "4") {
                this.formxq.sl4 = item.other1;
                dxcbje += Number(this.formxq.sl4) * Number(this.formtd.je4)
              }
            })
            this.formxq.cbje = dxcbje.toFixed(2);

            //查询客户价格
            Listkhjg(this.queryParams).then(response1 => {
              console.log(response1.rows)
              let dxxsje = 0;
              this.formxq.xsje = '0.00';
              response1.rows.forEach(item => {

                dxxsje += Number(this.formxq.sl1) * Number(item.other1)
                dxxsje += Number(this.formxq.sl2) * Number(item.other1)
                dxxsje += Number(this.formxq.sl3) * Number(item.other1)
                dxxsje += Number(this.formxq.sl4) * Number(item.other1)
              })
              this.formxq.xsje = dxxsje.toFixed(2);

            });
          });

        });
      }
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  }
}
</script>

<style scoped>
.sms-statistics {
  padding: 20px;
}

.info-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.help-text {
  color: #606266;
}

.link {
  color: #409EFF;
  text-decoration: none;
}

.action-button {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.action-button.primary {
  background: #409EFF;
  color: white;
  border: none;
}


.filter-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-actions {
  margin-left: auto;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.stats-summary {
  display: flex;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.success-rate {
  display: flex;
  align-items: baseline;
  margin-right: 32px;
}

.rate-label {
  color: #606266;
  margin-right: 8px;
}

.rate-value {
  font-size: 24px;
  font-weight: bold;
}

.rate-value.success {
  color: #67C23A;
}

.rate-value.failure {
  color: #F56C6C;
}

.rate-detail {
  color: #909399;
  margin-left: 4px;
}

.chart-legend {
  display: flex;
  gap: 16px;
  margin-left: auto;
}

.data-table {
  background: white;
  padding: 20px;
  border-radius: 4px;
}

/* Element UI Overrides */
:deep(.el-select) {
  width: 200px;
}

:deep(.el-date-editor--daterange) {
  width: 320px;
}
</style>
